<template>
  <div class="profile-page">
    <div class="user-info">
      <div class="container">
        <div class="row">
          <div class="col-xs-12 col-md-10 offset-md-1">
            <user-image :src="profile.image" class="user-img" />
            <h4>{{profile.username}}</h4>
            <p>{{profile.bio}}</p>
            <nuxt-link
              v-if="isCurrentLoginUser"
              class="btn btn-sm btn-outline-secondary action-btn"
              :to="{name: 'settings'}"
            >
              <i class="ion-gear-a"></i>Edit Profile Settings
            </nuxt-link>
            <button class="btn btn-sm btn-outline-secondary action-btn" @click="triggerFollow">
              <i class="ion-plus-round"></i>
              &nbsp;
              {{profile.following ? 'Unfollow' : 'Follow'}} {{profile.username}}
            </button>
          </div>
        </div>
      </div>
    </div>

    <div class="container">
      <div class="row">
        <div class="col-xs-12 col-md-10 offset-md-1">
          <div class="articles-toggle">
            <ul class="nav nav-pills outline-active">
              <li class="nav-item">
                <nuxt-link
                  class="nav-link"
                  exact
                  :class="{active: tab === 'my_articles'}"
                  :to="{
                  name: 'profile',
                  query: {
                    tab: 'my_articles'
                  },
                  params: {
                    username: username
                  }
                }"
                >My Articles</nuxt-link>
              </li>
              <li class="nav-item">
                <nuxt-link
                  class="nav-link"
                  exact
                  :class="{active: tab === 'favorited_articles'}"
                  :to="{
                  name: 'profile',
                  query: {
                    tab: 'favorited_articles'
                  },
                  params: {
                    username: username
                  }
                }"
                >Favorited Articles</nuxt-link>
              </li>
            </ul>
          </div>

          <div class="article-preview" v-if="!articles.length">No articles are here... yet.</div>
          <template v-else>
            <div class="article-preview" v-for="article in articles" :key="article.slug">
              <!--文章-->
              <article-item :article="article" />
            </div>
          </template>

          <nav>
            <ul class="pagination" v-for="p in pages" :key="p">
              <li
                class="page-item ng-scope"
                :class="{
              active: p === page
            }"
              >
                <nuxt-link
                  class="page-link"
                  :to="{
                  name: 'profile',
                  query: {
                    tab: tab,
                    page: p
                  },
                  params: {
                    username: username
                  }
                  }"
                >{{p}}</nuxt-link>
              </li>
            </ul>
          </nav>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getProfile, followUser, unfollowUser } from '@/api/profile.js'
import { getAllArticles } from '@/api/article.js'
import { mapState } from 'vuex'
import UserImage from '@/pages/components/userImage.vue'
import ArticleItem from '@/pages/components/article.vue'
export default {
  name: 'Profile',
  components: { UserImage, ArticleItem },

  watchQuery: ['page', 'tab'],

  async asyncData({ params, query }) {
    const { username } = params
    let { page = '1', limit = 10, tab = 'my_articles' } = query
    page = Number.parseInt(page)

    const queryData = {
      limit,
      offset: (page - 1) * limit,
    }

    if (tab === 'my_articles') {
      queryData['author'] = username
    } else if (tab === 'favorited_articles') {
      queryData['favorited'] = username
    }

    const [profileRes, articlesRes] = await Promise.all([
      getProfile(username),
      getAllArticles(queryData),
    ])

    let profile = {
      username: '',
      image: '',
      bio: '',
    }
    let articles = []
    let count = 0
    try {
      profile = profileRes.data.profile
      articles = articlesRes.data.articles
      count = articlesRes.data.articlesCount
    } catch {}

    return {
      username,
      profile,
      articles,
      count,
      tab,
      page,
      limit,
    }
  },

  data() {
    return {
      isUpdateFollowing: false,
    }
  },

  computed: {
    ...mapState(['user']),
    isCurrentLoginUser() {
      if (!this.user) return false
      return this.profile.username === this.user.username
    },
    pages() {
      return Math.ceil(this.count / this.limit)
    },
  },

  methods: {
    async triggerFollow() {
      if (!this.user) {
        this.$router.push({
          name: 'login',
        })
        return
      }
      this.isUpdateFollowing = true
      const { username, following } = this.profile
      const request = following ? followUser : unfollowUser
      const { data } = await request(username)
      if (data && data.profile) {
        this.profile.following = data.profile.following
      }
      this.isUpdateFollowing = false
    },
  },
}
</script>